package com.mall.pay.services;

import com.mall.order.OrderCoreService;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

import static com.mall.pay.constants.PayChannelEnum.ALI_PAY;
import static com.mall.pay.constants.PayResultEnum.*;

@Slf4j
@Component
@Service
@Transactional
public class PayCorServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;

    @Reference(timeout = 30000,check = false)
    OrderCoreService orderCoreService;

    @Autowired
    PaymentMapper paymentMapper;

    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {

        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();

        String fileName = payHelper.test_trade_precreate(request);
        if (fileName == null) {
            // 获取支付二维码失败
            alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            return alipaymentResponse;
        }

        // 获取支付二维码成功

        // 向tb_payment表中插入一条记录，记录订单的支付信息 PAY_PROCESSING
        Payment payment = new Payment();
        payment.setStatus(PAY_PROCESSING.getCode());
        payment.setOrderId(request.getTradeNo());
        payment.setPayerUid(request.getUserId());
        payment.setPayerAmount(request.getTotalFee());
        payment.setOrderAmount(request.getOrderFee());
        payment.setPayWay(request.getPayChannel());
        payment.setCreateTime(new Date());
        payment.setUpdateTime(new Date());
        paymentMapper.insertSelective(payment);

        alipaymentResponse.setQrCode(fileName);
        alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());


        return alipaymentResponse;
    }

    @Override
    public AlipayQueryRetResponse queryAlipayRet(PaymentRequest request) {
        boolean paySuccess = payHelper.test_trade_query(request);

        if (paySuccess) {
            // 支付成功
            // 1. 修改tb_payment支付记录的支付信息，PAY_SUCCESS，支付成功的时间，支付完成时间
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId",request.getTradeNo());
            List<Payment> payments = paymentMapper.selectByExample(example);
            for (Payment payment : payments) {
                payment.setStatus(PAY_SUCCESS.getCode());
                payment.setPaySuccessTime(new Date());
                payment.setCompleteTime(new Date());
                payment.setUpdateTime(new Date());
                paymentMapper.updateByPrimaryKey(payment);
            }
            // 2. 修改订单的状态, 支付成功 ORDER_STATUS_PAYED
            orderCoreService.payOrderSuccess(request.getTradeNo());
            // 3. 修改库存，根据订单商品条目，扣减对应的锁定库存
            orderCoreService.updateLockCount(request.getTradeNo());
            // 4. 返回响应
            AlipayQueryRetResponse response = new AlipayQueryRetResponse();
            response.setCode(PayReturnCodeEnum.SUCCESS.getCode());
            response.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
            return response;
        } else {
            // 支付失败
            // 1. 修改tb_payment支付记录的支付信息, PAY_FAIL
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId",request.getTradeNo());
            List<Payment> payments = paymentMapper.selectByExample(example);
            for (Payment payment : payments) {
                payment.setStatus(PAY_FAIL.getCode());
                payment.setUpdateTime(new Date());
                paymentMapper.insertSelective(payment);
            }
            // 2. 返回支付失败的响应
            AlipayQueryRetResponse response = new AlipayQueryRetResponse();
            response.setCode(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getCode());
            response.setMsg(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getMsg());
            return response;

        }
    }
}
